# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html


# 中间件文件
from scrapy.http import Response
from scrapy import signals
from scrapy.utils.response import response_httprepr
# useful for handling different item types with a single interface
# 用于通过单一接口处理不同类型的Item
from itemadapter import is_item, ItemAdapter


class CcgpSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.
    # 并非所有方法都需要定义。如果未定义某个方法，
    # Scrapy会认为该爬虫中间件不会修改传入的对象。

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        # 该方法被Scrapy用来创建你的爬虫
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.
        # 对每个经过爬虫中间件并进入爬虫的响应调用

        # Should return None or raise an exception.
        # 应该返回None或引发异常
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.
        # 在爬虫处理完响应后，用返回的结果调用

        # Must return an iterable of Request, or item objects.
        # 必须返回Request或item对象的可迭代对象
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.
        # 当爬虫或其他爬虫中间件的process_spider_input()方法引发异常时调用

        # Should return either None or an iterable of Request or item objects.
        # 应该返回None或Request/item对象的可迭代对象
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn't have a response associated.
        # 用爬虫的初始请求调用，工作方式类似于process_spider_output()方法，
        # 只是它没有关联的响应
        print('用爬虫的初始请求调用', start_requests)
        # Must return only requests (not items).
        # 必须只返回requests（而不是items）
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class CcgpDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    # 并非所有方法都需要定义。如果未定义某个方法，
    # Scrapy会认为该下载器中间件不会修改传入的对象。

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        # 该方法被Scrapy用来创建你的爬虫
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.
        # 对每个经过下载器中间件的请求调用
        print("请求拦截器", request)
        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        # 必须：
        # - 返回None：继续处理该请求
        # - 或返回Response对象
        # - 或返回Request对象
        # - 或引发IgnoreRequest：将调用已安装下载器中间件的process_exception()方法
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.
        # 用下载器返回的响应调用
        print("响应拦截器", response)
        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        # 必须：
        # - 返回Response对象
        # - 或返回Request对象
        # - 或引发IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.
        # 当下载处理器或其他下载器中间件的process_request()方法引发异常时调用

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        # 必须：
        # - 返回None：继续处理该异常
        # - 返回Response对象：停止process_exception()链
        # - 返回Request对象：停止process_exception()链
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

    def response_to_dict(self, response):
        """安全转换Response对象为字典"""
        try:
            # 检查response是否为合法对象
            if not isinstance(response, Response):
                return {'error': 'Invalid response object'}
            # 处理可能的二进制数据
            http_repr = response_httprepr(response)

            return {
                'raw_response': http_repr.decode('utf-8', errors='replace'),  # 强制UTF-8解码
                'status': response.status,
                'url': response.url,
                'headers': dict(response.headers),  # 添加头信息
                'effective_url': response.url  # 最终URL（考虑重定向）
            }
        except Exception as e:
            # 捕获所有异常并返回错误信息
            return {
                'error': str(e),
                'response_type': type(response).__name__,
                'available_attrs': dir(response)  # 调试用：打印对象属性
            }


